<template>
  <div class="home">
    <!-- <QuillEditor
      ref="myQuillEditor"
      theme="snow"
      v-model:content="content"
      :options="data.editorOption"
      contentType="html"
      @update:content="setValue()"
    /> -->
    <QuillEditor
      ref="myQuillEditor"
      theme="snow"
      v-model:content="value"
      :options="data.editorOption"
      contentType="html"
      @update:content="setValue()"
    />
    <input
      type="file"
      hidden
      accept=".jpg,.png,.jpeg"
      ref="fileBtn"
      @change="handleUpload"
    />
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import axios from "axios";
import { uploadUrl } from "@/api/common";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import {
  reactive,
  onMounted,
  ref,
  toRaw,
  watch,
  getCurrentInstance,
  computed,
} from "vue";

const props = defineProps(["value"]);
const emit = defineEmits(["update:value", "updateValue"]);
const constt = ref("");
// const content = computed({
//   get() {
//     return props.value;
//   },
//   set(v) {
//     // constt.value = v;
//     emit("update:value", v);
//   },
// });
// const upload = ref();
const myQuillEditor = ref();
const headers = {
  Authorization: "Bearer " + getToken(),
};
// 通过watch监听回显，笔者这边使用v-model:content 不能正常回显
// watch(
//   () => props.value,
//   (val) => {
//     // console.log("val", val);
//     // toRaw(myQuillEditor.value).setHTML(val);
//     emit("updateValue", val);
//   }
//   // { immediate: true }
// );

const { proxy } = getCurrentInstance();
const fileBtn = ref();
const baseUrl =
  import.meta.env.VITE_APP_ENV == "development"
    ? import.meta.env.VITE_APP_BASE_API
    : window.location.origin;
// const uploadUrl = baseUrl + "/api/commin/uploadFile"; // 上传的图片服务器地址
const data = reactive({
  content: "",
  editorOption: {
    modules: {
      toolbar: [
        ["bold", "italic", "underline", "strike"],
        [{ size: ["small", false, "large", "huge"] }],
        [{ font: [] }],
        [{ align: [] }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ indent: "-1" }, { indent: "+1" }],
        [{ header: 1 }, { header: 2 }],
        ["image"],
        [{ direction: "rtl" }],
        [{ color: [] }, { background: [] }],
      ],
    },
    placeholder: "请输入内容...",
  },
});

const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click();
    // console.log(proxy.$refs.upload.submit());
    // upload.value.click();
    // upload.$children[0].$refs.input.click();
  }
};
// 抛出更改内容，此处避免出错直接使用文档提供的getHTML方法
const setValue = () => {
  const text = toRaw(myQuillEditor.value).getHTML();
  // console.log("text", text);
  emit("updateValue", text);
  // emit("update:value", text);
};
function handleBeforeUpload(file) {
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < this.fileSize;
  if (!isLt) {
    proxy.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
    return false;
  } else {
    return true;
  }
}
function handleUploadError() {
  proxy.$message.error("图片插入失败");
}
function handleUploadSuccess(res, file) {
  // console.log(999, res);
  // 获取富文本组件实例
  // let quill = toRaw(myQuillEditor.value).getQuill();
  const quill = toRaw(myQuillEditor.value).getQuill();
  // 如果上传成功
  if (res.code == 200) {
    // 获取光标所在位置
    let length = quill.getSelection().index;
    // 插入图片  res.url为服务器返回的图片地址
    console.log(baseUrl + "/" + res.data.url);
    quill.insertEmbed(length, "image", baseUrl + "/" + res.data.url);
    // 调整光标到最后
    quill.setSelection(length + 1);
  } else {
    proxy.$message.error("图片插入失败");
  }
}
const handleUpload = (e) => {
  const fileSize = 5;
  const files = Array.prototype.slice.call(e.target.files);
  console.log(files, "files");
  if (!files) {
    return;
  }
  const isLt = files.size / 1024 / 1024 >= fileSize;
  if (isLt) {
    proxy.$message.error(`上传文件大小不能超过 ${fileSize} MB!`);
    return false;
  }
  // axios
  const formdata = new FormData();
  formdata.append("file", files[0]);
  axios
    .post(uploadUrl, formdata, {
      "Content-type": "multipart/form-data",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.code == 200) {
        // console.log(res.data);
        const quill = toRaw(myQuillEditor.value).getQuill();
        const length = quill.getSelection().index;
        quill.insertEmbed(length, "image", baseUrl + "/" + res.data.data.url);
        quill.setSelection(length + 1);
      } else {
        proxy.$message.error(`上传失败,${res.data.msg}`);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
// 初始化编辑器
onMounted(() => {
  const quill = toRaw(myQuillEditor.value).getQuill();
  if (myQuillEditor.value) {
    quill.getModule("toolbar").addHandler("image", imgHandler);
  }
});
</script>

<style scoped lang="scss">
.home {
  width: 100%;
}
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>
